package com.example.smartvillage.cunmin;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProvider;

import com.example.smartvillage.MainViewModel;
import com.example.smartvillage.R;
import com.example.smartvillage.onenet.MyOneNetApi;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.gson.JsonArray;

import java.util.Objects;

public class LeaveHomeFragment extends BottomSheetDialogFragment {

    static final String TAG = "离家模式";

    MainViewModel model;
    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;
    MyOneNetApi myOneNetApi;

    public LeaveHomeFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        model = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        myOneNetApi = Objects.requireNonNull(model.getMyOneNetApi().getValue());
        sharedPref = getContext().getSharedPreferences(
                getString(R.string.preference_file_key), Context.MODE_PRIVATE);

        //每次进入更新数据
        String dataStreamId = "离家模式";
        myOneNetApi.getDataStreams(dataStreamId, response -> {
            if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                JsonArray obj = response.body().get("data").getAsJsonArray();
                boolean newState = (obj.get(0).getAsJsonObject().get("current_value").getAsInt() == 1);
                Log.d(TAG, "获取的离家模式状态：" + newState);
                model.setLeaveHomeState(newState);
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_leave_home, container, false);

        MaterialCheckBox checkBoxLight = view.findViewById(R.id.leave_home_light);
        checkBoxLight.setChecked(sharedPref.getBoolean("leave_home_manage_light", true));

        MaterialCheckBox checkBoxWindow = view.findViewById(R.id.leave_home_window);
        checkBoxWindow.setChecked(sharedPref.getBoolean("leave_home_manage_window", true));

        MaterialButton buttonSwitch = view.findViewById(R.id.leave_home_switch);

        checkBoxLight.setOnCheckedChangeListener(lightOnCheckedChangeListener);
        checkBoxWindow.setOnCheckedChangeListener(windowOnCheckedChangeListener);
        buttonSwitch.setOnClickListener(switchOnClickListener);

        model.getLeaveHomeState().observe(this, aBoolean -> {
            if (aBoolean) {
                buttonSwitch.setText("关闭");
            }
            else {
                buttonSwitch.setText("启动");
            }
        });


        return view;
    }

    //灯光管理监听
    CompoundButton.OnCheckedChangeListener lightOnCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editor = sharedPref.edit();
            editor.putBoolean("leave_home_manage_light", isChecked);
            editor.apply();
        }
    };
    //窗户管理监听
    CompoundButton.OnCheckedChangeListener windowOnCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editor = sharedPref.edit();
            editor.putBoolean("leave_home_manage_window", isChecked);
            editor.apply();
        }
    };
    //切换按钮监听
    View.OnClickListener switchOnClickListener = v -> {
        final boolean[] state = {model.getLeaveHomeState().getValue()};
        //当前状态为开，则关闭离家模式，否则启动离家模式
        String command = "leavhome:"+(state[0] ?"0":"1");

        //在线命令
        myOneNetApi.sendCommand(0, 0, command, response -> {
            if (response.body() != null && response.body().get("errno").getAsInt() == 0) {
                if (state[0]) {
                    Toast.makeText(getContext(), "已关闭离家模式", Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(getContext(), "已启动离家模式", Toast.LENGTH_SHORT).show();
                }

                //更新ViewModel中的数据
                state[0] = !state[0];
                model.setLeaveHomeState(state[0]);
            }
            else if (response.body().get("errno").getAsInt() == 10) {
                Toast.makeText(getContext(), "设备不在线", Toast.LENGTH_SHORT).show();
            }
        });
    };
}